const e = require('express');
var express = require('express');
var router = express.Router();
const studentService = require('../service/studentService');

router.get('/',async function(req,res){
    let {type,value,current,size,callback} = req.query;
    let searchObj = {};
    if(type){
        if(type == "age"){
            searchObj[type] = value;
        }else{
            searchObj[type] = {$regex:value};
        }
        
    }
    let data;
    if(type == 'className'){
        data = await studentService.findByClassName(value
            ,{current:current||1,size:size||3});
    }else{
        data = await studentService.find(searchObj
            ,{current:current||1,size:size||3});
    }
    // res.send(`${callback}(${JSON.stringify(data)})`)
    res.send(data);
});
router.get('/:id',async function(req,res){
    let id = req.params.id;
    let data = await studentService.findById(id);
    res.send(data);
});
/**
 * @swagger
 * /students:
 *    post:
 *      tags:
 *      - students
 *      summary: 增加学生
 *      requestBody:
 *        required: true
 *        content:
 *          application/x-www-form-urlencoded:
 *            schema:
 *              type: object
 *              properties:
 *                name:          
 *                  type: string
 *                age:    
 *                  type: integer
 *                gender:
 *                  type: string
 *      responses:
 *        200:
 *          description: 操作成功
 *        401:
 *          description: 权限不足
 * */
router.post('/',async function(req,res){
    let data = await studentService.insert(req.body);
    res.send(data);
});
/**
 * @swagger
 * /students/{id}:
 *    put:
 *      tags:
 *      - students
 *      summary: 修改学生
 *      parameters:
 *      - name: id
 *        in: path
 *        description: 学生id
 *        required: true
 *      requestBody:
 *        required: true
 *        content:
 *          application/x-www-form-urlencoded:
 *            schema:
 *              type: object
 *              properties:
 *                name:          
 *                  type: string
 *                age:    
 *                  type: integer
 *                gender:
 *                  type: string
 *      responses:
 *        200:
 *          description: 操作成功
 *        401:
 *          description: 权限不足
 * */
router.put('/:id',async function(req,res){
    let id = req.params.id;
    if(!req.body.cls){
        delete req.body.cls;
    }
    
    console.log(id,req.body);
    let data = await studentService.update(id,req.body);
    res.send(data);
});
router.delete('/:id',async function(req,res){
    let data = await studentService.delete(req.params.id);
    res.send(data);
})

module.exports = router;